<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            :options="cateList"
            :props="cateProps"
            v-model="cateId"
            @change="selectCate"
            clearable
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeTab" @tab-click="tabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="isAddShow = true"
            >添加参数</el-button
          >
          <el-table :data="manyParams" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="sc">
                <el-tag
                  v-for="(tag, i) in sc.row.attr_vals"
                  :key="i"
                  closable
                  @close="doDelTag(sc.row, i)"
                >
                  {{ tag }}</el-tag
                >
                <el-input
                  v-el-focus
                  v-if="sc.row.inputShow"
                  v-model="sc.row.inputText"
                  size="small"
                  class="tagInput"
                  @keyup.native="doAddTag(sc.row, $event)"
                  @blur="
                    sc.row.inputShow = false
                    sc.row.inputText = ''
                  "
                >
                </el-input>
                <el-tag @click="sc.row.inputShow = true" class="btnAdd" v-else>
                  + NewTag
                </el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="sc">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEdit(sc.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="doDel(sc.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="isAddShow = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyParams" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="sc">
                <el-tag
                  v-for="(tag, i) in sc.row.attr_vals"
                  :key="i"
                  closable
                  @close="doDelTag(sc.row, i)"
                >
                  {{ tag }}</el-tag
                >
                <el-input
                  v-el-focus
                  v-if="sc.row.inputShow"
                  v-model="sc.row.inputText"
                  size="small"
                  class="tagInput"
                  @keyup.native="doAddTag(sc.row, $event)"
                  @blur="
                    sc.row.inputShow = false
                    sc.row.inputText = ''
                  "
                >
                </el-input>
                <el-tag @click="sc.row.inputShow = true" class="btnAdd" v-else>
                  + NewTag
                </el-tag>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="sc">
                <el-button size="mini" type="primary" icon="el-icon-edit"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="doDel(sc.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="isAddShow"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form :model="addModel" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddShow = false">取 消</el-button>
        <el-button type="primary" @click="doAddParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="isEditShow"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 添加参数的对话框 -->
      <el-form
        :model="addModel"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addModel.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="doEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      cateId: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover',
      },
      activeTab: 'many',
      manyParams: [],
      onlyParams: [],
      isAddShow: false,
      addModel: {
        attr_id: -1,
        attr_name: '',
      },
      isEditShow: false,
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'categories',
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.cateList = res.data
    },
    async selectCate() {
      this.getCateparams()
    },
    tabClick() {
      this.getCateparams()
    },
    async getCateparams() {
      if (this.cateId.length < 3) {
        this.cateId = []
        this.manyParams = []
        this.onlyParams = []
        return this.$msgBox.alert('必须选择第三鸡', '系统警告')
      }
      const { data: res } = await this.$axios({
        method: 'get',
        url: `categories/${this.selectId}/attributes`,
        params: {
          sel: this.activeTab,
        },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      res.data.forEach((item) => {
        if (item.attr_vals.trim().length === 0) {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
        item.inputShow = false
        item.inputText = ''
      })
      if (this.activeTab === 'many') {
        this.manyParams = res.data
      } else {
        this.onlyParams = res.data
      }
    },
    async doAddParam() {
      const { data: res } = await this.$axios({
        method: 'post',
        url: `categories/${this.selectId}/attributes`,
        data: {
          attr_name: this.addModel.attr_name,
          attr_sel: this.activeTab,
        },
      })
      if (res.meta.status !== 201) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
      this.isAddShow = false
      this.getCateparams()
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    showEdit(row) {
      this.isEditShow = true
      this.addModel.attr_name = row.attr_name
      this.addModel.attr_id = row.attr_id
    },
    async doEdit() {
      const { data: res } = await this.$axios({
        url: `categories/${this.selectId}/attributes/${this.addModel.attr_id}`,
        method: 'put',
        data: {
          attr_name: this.addModel.attr_name,
          attr_sel: this.activeTab,
        },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.isEditShow = false
      this.getCateparams()
      this.$msg.success(res.meta.msg)
    },
    // 重置修改的表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    async doDel(paramId) {
      const { data: res } = await this.$axios({
        url: `categories/${this.selectId}/attributes/${paramId}`,
        method: 'delete',
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.getCateparams()
      this.$msg.success(res.meta.msg)
    },
    async doAddTag(row, e) {
      if (e.code !== 'Enter') return
      row.attr_vals.push(row.inputText)
      const { data: res } = await this.$axios({
        url: `categories/${row.cat_id}/attributes/${row.attr_id}`,
        method: 'put',
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
      row.inputText = ''
      row.inputShow = false
    },
    async doDelTag(row, i) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$axios({
        method: 'put',
        url: `categories/${row.cat_id}/attributes/${row.attr_id}`,
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        },
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.$msg.success(res.meta.msg)
    },
  },
  created() {
    this.getCateList()
  },
  computed: {
    selectId() {
      return this.cateId[2]
    },
    isDisabled() {
      return this.cateId.length < 3
    },
    titleText() {
      if (this.activeTab === 'many') {
        return '动态参数'
      }
      return '静态参数'
    },
  },
}
</script>
<style scoped>
.tagInput {
  width: 120px;
}
</style>